const { MongoClient, ObjectId } = require('mongodb')
// Replace the uri string with your connection string
const uri = 'mongodb://127.0.0.1:27017'
const client = new MongoClient(uri)

async function run() {
  try {
    const database = client.db('test')
    const mycollection = database.collection('mycollection')
    // 1.插入文档
    // await database.collection('mycollection').drop() // 删除集合
    // let list = [
    //   { _id: new ObjectId('687b426890183a5a25b0b2b0'), item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' },
    //   { item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' },
    //   { item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' },
    //   { item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' },
    //   { item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }
    // ]
    // const ret = await mycollection.insertMany(list)
    // console.log(ret)

    // 2.查询文档 findOne
    // const ret = await mycollection.findOne({
    //   item: 'notebook'
    // })
    // console.log(ret)

    // 2.查询文档 find
    // const ret = await mycollection.find().toArray()
    // console.log(ret)

    // 3.更新文档
    // const ret = await mycollection.updateOne(
    //   {
    //     _id: new ObjectId('687b426890183a5a25b0b2b0')
    //   },
    //   {
    //     $set: {
    //       item: 'zh'
    //     }
    //   }
    // )
    // console.log(ret)

    // 删除
    // const ret = await mycollection.deleteOne({
    //   _id: new ObjectId('687b426890183a5a25b0b2b0')
    // })
    // console.log('delete:', ret.deletedCount)
    // 删除全部
    // const ret = await mycollection.deleteMany()
    // console.log('delete:', ret.deletedCount)
  } catch (err) {
    // 连接失败
    console.log('连接失败', err)
  } finally {
    await client.close()
  }
}

run()
